<script setup lang="ts">
import { ref, watch } from "vue";
import { dateStartFormat, dateEndFormat, getMonthByLastTime } from "@/tools";
import { ModelValueType } from "element-plus";

//日期
const timerange = ref()
//最终时间结果，传给上一级用于查询
const timeResult = ref<ModelValueType>()

interface Props {
    modelValue?: ModelValueType
}
interface Emits {
    (t: 'update:modelValue', b?: ModelValueType): void
}
const props = defineProps<Props>()

watch(() => props.modelValue, (nv) => {
    timerange.value = nv
})

const emit = defineEmits<Emits>()
//月日选则改变后的时间
function handeTimechange(value?: ModelValueType) {
    if (!value) {
        timeResult.value = ['', '']
    } else if (Array.isArray(value)) {
        const [start, end] = value;
        timeResult.value = [dateStartFormat(start as Date), dateEndFormat(end as Date)]
    }
    emit('update:modelValue', timeResult.value)
}
const shortcuts = ref([
    {
        text: '今天', value: () => {
            let tempdate = new Date()
            tempdate.setHours(0)
            tempdate.setMinutes(0)
            tempdate.setSeconds(0)
            let tempEndTime = new Date()
            tempEndTime.setHours(23)
            tempEndTime.setMinutes(59)
            tempEndTime.setSeconds(59)
            return [tempdate, tempEndTime]
        }
    },
    {
        text: '昨天', value: () => {
            const startTime = getMonthByLastTime(1, new Date(), 'day')
            startTime.setHours(0)
            startTime.setMinutes(0)
            startTime.setSeconds(0)
            let tempEndTime = new Date()
            tempEndTime.setHours(23)
            tempEndTime.setMinutes(59)
            tempEndTime.setSeconds(59)
            return [startTime, tempEndTime]
        }
    },
    {
        text: '最近7天', value: () => {
            let tempdate = new Date()
            return [getMonthByLastTime(7, tempdate, 'day'), tempdate]
        }
    },
    {
        text: '最近30天', value: () => {
            let tempdate = new Date()
            return [getMonthByLastTime(30, tempdate, 'day'), tempdate]
        }
    },

])
</script>
<template>
    <ElDatePicker v-model="timerange" type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期"
        end-placeholder="结束日期" :shortcuts="shortcuts" @change="handeTimechange"></ElDatePicker>
</template>